import config from '../../config/index'
import { getPhoneNumber, wxUserLogin, getNewUser } from '../../api/user'
import { getCustomerPhone } from '../../api/customer'
import { setToken, setUserInfo, getUserInfo, removeToken, removeUserInfo, getToken } from '../../utils/storage'
import { checkLogin } from '../../utils/loginStatus'
import { roles } from '../../enums/role'
//@ts-ignore
import Dialog from '@vant/weapp/dialog/dialog'
Page({
  data: {
    userInfo: {} as User,
    show: false,
    agree: false,
    roles,
    role_label: '',
    config,
    loading: false,
    kefu_phone: '',
    kefu_wx: '',
    hide_phone: '',
    showPrivacy: false,
    privacyContractName: '',
    showCustomer: false
  },
  callPhone() {
    if (this.data.kefu_phone === '') {
      wx.showToast({ title: '拨打失败请重试', icon: 'none' })
      return
    }
    wx.makePhoneCall({
      phoneNumber: this.data.kefu_phone,
      fail: () => {
        wx.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  },
  copyWx() {
    if (this.data.kefu_wx === '') {
      wx.showToast({
        title: '复制失败',
        icon: 'none'
      })
      return
    }
    wx.setClipboardData({
      data: this.data.kefu_wx
    })
  },
  handleShow() {
    this.setData({
      show: !this.data.show
    })
  },
  logout() {
    Dialog.confirm({
      title: '退出登录',
      message: '确认退出登录？'
    })
      .then(() => {
        // on confirm
        removeToken()
        removeUserInfo()
        this.setData({
          userInfo: {} as any
        })
        wx.showToast({
          title: '退出成功',
          icon: 'none'
        })
      })
      .catch(() => { });
  },
  async getPhoneNumber(e: any) {
    if (!e.detail.code) {
      wx.showToast({
        title: '已拒绝授权',
        icon: 'none'
      })
      return
    }
    if (this.data.agree === false) {
      wx.showToast({
        title: '请勾选并阅读协议',
        icon: 'none'
      })
      return
    }
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      let data = {
        code: e.detail.code
      }
      this.setData({
        loading: true
      })
      const res = await getPhoneNumber(data)
      let loginData = {
        phone: res.data.phone_info.phoneNumber
      }
      const loginRes = await wxUserLogin(loginData)
      if (loginRes.statusCode === config.CREATED_CODE) {
        setToken(loginRes.data.token)
        setUserInfo(JSON.stringify(loginRes.data.user))
        wx.showToast({
          icon: 'none',
          title: '登录成功'
        })
        this.setData({
          loading: false
        })
        this.getData()
        this.handleShow()
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '获取电话号码失败'
      })
    }

  },
  onCustomerClose() {
    this.setData({
      showCustomer: !this.data.showCustomer
    })
  },
  onChange(event: any) {
    this.setData({
      agree: event.detail,
    });
  },
  getData() {
    const user = getUserInfo()
    if (user) {
      this.setData({
        userInfo: JSON.parse(user),
        role_label: this.data.roles.find(item => item.value === JSON.parse(user).role)!.label
      })
    }
  },
  async updateUser() {
    if (!getToken()) {
      this.setData({
        userInfo: {} as User
      })
      return
    }
    if (this.data.userInfo.id) {
      const res = await getNewUser(this.data.userInfo.id)
      if (res.statusCode === config.SUCCESS_CODE) {
        setUserInfo(JSON.stringify(res.data))
        this.getData()
      }
    }
  },
  toInfo() {
    wx.navigateTo({
      url: '/pages/userInfo/userInfo'
    })
  },
  toPath(e: WechatMiniprogram.TouchEvent) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url
    })
  },
  //privacyPolicy
  toPolicy() {
    wx.downloadFile({
      url: config.BaseUrl + '/pdfs/privacyPolicy.pdf',
      success: (res) => {
        wx.openDocument({
          filePath: res.tempFilePath
        })
      }
    })
  },
  //userAgreement
  toAgreement() {
    wx.downloadFile({
      url: config.BaseUrl + '/pdfs/userAgreement.pdf',
      success: (res) => {
        wx.openDocument({
          filePath: res.tempFilePath
        })
      }
    })
  },
  async initCustomer() {
    const res = await getCustomerPhone()
    if (res.statusCode === config.SUCCESS_CODE) {
      if (res.data === null) return
      let customer_data = JSON.parse(res.data)
      this.setData({
        kefu_phone: customer_data.customer_phone,
        kefu_wx: customer_data.customer_wx,
        hide_phone: customer_data.customer_phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      })
    }
  },
  saveTemplate() {
    Dialog.confirm({
      title: '下载租赁模板',
      message: '确认后将打开租赁模板文件，您可以在打开后点击右上角打开通过其他应用保存此文件'
    }).then(() => {
      wx.downloadFile({
        url: config.BaseUrl + '/pdfs/template.docx',
        success: (res) => {
          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu: true
          })
        }
      })
    }).catch(() => { })
  },
  //用户隐私相关
  // checkPrivacy() {
  //   wx.getPrivacySetting({
  //     success: res => {
  //       // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
  //       if (res.needAuthorization) {
  //         // 需要弹出隐私协议
  //         this.setData({
  //           showPrivacy: true,
  //           privacyContractName: res.privacyContractName
  //         })
  //       } else { }
  //     },
  //     fail: () => { },
  //     complete: () => { }
  //   })
  // },
  async onShow() {
    this.getData()
    const res = await checkLogin()
    if (res === false && res !== undefined) {
      wx.showToast({ title: '检测到跨设备登录，已退出登录', icon: 'none' })
      removeToken()
      removeUserInfo()
      this.setData({
        userInfo: {} as User
      })
      return
    }
    this.updateUser()
  },
  onLoad() {
    this.initCustomer()
    // this.checkPrivacy()
  }
})